<template>
    <section>
        <!--列表-->
        <div class="panel">
            <div class="panel-head">
                <strong><i class="el-icon-date"/><span class="title">首页配置</span></strong>
            </div>
            <div class="body-content">
                <!-- tab栏数据 -->
                <el-tabs v-model="activeName" @tab-click="handleClick" type="card">
                    <el-tab-pane v-for="item in tabapiMap" :label="item.tabName" :name="item.code" :key="item.code"/>
                </el-tabs>
                <el-button class="btn-margin" type="primary" size="small" @click="addModel">新增</el-button>
                <!-- 展示数据 -->
                <el-table v-show="activeName != '2003'" :data="tableData" border v-loading="listLoading" element-loading-text="拼命加载中">
                    <el-table-column label="序号" width="70">
                        <template slot-scope="scope">
                            <el-popover trigger="click" placement="top">
                                <span>autoId: {{ scope.row.autoId }}</span>
                                <div slot="reference">
                                    {{scope.$index + 1}}
                                </div>
                            </el-popover>
                        </template>                    
                    </el-table-column>
                    <el-table-column prop="title" label="名称" width="150"/>
                    <el-table-column label="图标链接">
                        <template slot-scope="scope">
                            <img :src="scope.row.imageUrl" alt="图标" :style="imageClass"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="链接" width="80">
                        <template slot-scope="scope">
                            <el-popover trigger="hover" placement="top">
                                <p>跳转链接: {{ scope.row.link }}</p>
                                <div slot="reference" class="name-wrapper">
                                    <el-tag size="medium">查看</el-tag>
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="规则"/>
                    <el-table-column label="生效时间" width="160">
                        <template slot-scope="scope">
                            {{formatDate(scope.row.activateTime)}}<br/>至<br/>{{formatDate(scope.row.expireTime)}}
                        </template>
                    </el-table-column>
                    <el-table-column v-if="activeName === '1002' " prop="hotTag" label="角标"/>
                    <el-table-column prop="sort" label="顺序" width="50"/>
                    <el-table-column label="状态" width="100">
                        <template slot-scope="scope">
                            {{scope.row.disabled == 1 ? "禁用" : "启用"}}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template slot-scope="scope">
                            <el-button type="text" @click="editModel(scope.row)">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 文章列表 -->
                <el-table v-show="activeName == '2003'" :data="articleList" border v-loading="listLoading" element-loading-text="拼命加载中">
                    <!-- <el-table-column type="index" label="序号" width="70"/> -->
                    <el-table-column label="序号" width="70">
                        <template slot-scope="scope">
                            <el-popover trigger="click" placement="top">
                                <span>autoId: {{ scope.row.autoId }}</span>
                                <div slot="reference">
                                    {{scope.$index + 1}}
                                </div>
                            </el-popover>
                        </template>                    
                    </el-table-column>
                    <el-table-column prop="mainTitle" label="主标题"/>
                    <el-table-column prop="subTitle" label="副标题" width="150"/>
                    <el-table-column label="图片链接">
                        <template slot-scope="scope">
                            <img :src="scope.row.imageUrl" alt="图标" :style="{width: '100px'}"/>
                        </template>
                    </el-table-column>
                    <el-table-column label="活动链接" width="80">
                        <template slot-scope="scope">
                            <el-popover trigger="hover" placement="top">
                                <p>{{ scope.row.link }}</p>
                                <div slot="reference" class="name-wrapper">
                                    <el-tag size="medium">查看</el-tag>
                                </div>
                            </el-popover>
                        </template>
                    </el-table-column>

                    <el-table-column label="更新时间" width="160">
                        <template slot-scope="scope">
                            {{scope.row.lastModifyTime}}
                        </template>
                    </el-table-column>

                    <el-table-column label="置顶" width="50">
                        <template slot-scope="scope">
                            {{scope.row.top == 1 ? "是" : "否"}}
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" width="100">
                        <template slot-scope="scope">
                            {{scope.row.status == 1 ? "启用" : "禁用"}}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80">
                        <template slot-scope="scope">
                            <el-button type="text" @click="editModelArticle(scope.row)">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 文章列表分类 -->
                <el-pagination v-show="this.activeName === '2003'" @current-change="changeArticleListPage" :current-page="articleListCurPage" :page-size="10" layout="total, prev, pager, next" :total="articleListTotalPage"/>
                <!-- 编辑新增文章弹窗 -->
                <el-dialog title="资讯文章" :visible.sync="articleDialogFormVisible" width="50%" @close="closeDailog">
                    <el-form>

                        <el-form-item label="主标题" :label-width="formLabelWidth">
                            <el-input v-model.trim="articleFormData.mainTitle" :maxlength="12" placeholder="最多12个字符" style="width:250px;" size="small"/>
                        </el-form-item>

                        <el-form-item label="副标题" :label-width="formLabelWidth">
                            <el-input v-model.trim="articleFormData.subTitle" :maxlength="20" placeholder="最多20个字符" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item label="文章类型" :label-width="formLabelWidth">
                            <el-select v-model="articleFormData.type" size='small' placeholder="选择文章类型" style="width: 150px">
                                <el-option v-for="item in articleTypes" :key="item.code" :label="item.value" :value="item.code"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="图片链接" :label-width="formLabelWidth">
                            <el-form :inline="true">
                                <el-form-item>
                                    <el-input v-model.trim="articleFormData.imageUrl" style="width:250px;" size="small"/>
                                </el-form-item>
                                <el-form-item>
                                    <el-upload class="upload-demo" :headers="headers" :with-credentials="withCredentials" name="multipartFile" ref="upload" :action="uploadURL" :on-exceed="handleExceed" :on-remove="handleRemove" :on-success='handleSuccess' :file-list="fileList" :limit="1" :before-upload="beforeAvatarUpload">
                                        <el-button size="small" type="primary">点击上传</el-button>
                                    </el-upload>
                                </el-form-item>
                            </el-form>
                        </el-form-item>
                        <el-form-item :label-width="formLabelWidth">
                            只能上传jpg/jpeg/png文件，且不超过10M
                        </el-form-item>
                        <el-form-item label="活动链接" :label-width="formLabelWidth">
                            <el-input v-model.trim="articleFormData.link" style="width:250px;" size="small"/>
                        </el-form-item>

                        <el-form-item label="是否置顶" :label-width="formLabelWidth">
                            <el-select v-model="articleFormData.top" style="width:150px;" placeholder="是否置顶" size="small">
                                <el-option label="是" value=1 />
                                <el-option label="否" value=0 />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="是否启用" :label-width="formLabelWidth">
                            <el-select v-model="articleFormData.status" style="width:150px;" placeholder="请选择活动状态" size="small">
                                <el-option label="启用" value=1 />
                                <el-option label="禁用" value=0 />
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="small" @click="articleFormCancel">取 消</el-button>
                        <el-button size="small" type="primary" @click="articleFormConfirm">确 定</el-button>
                    </div>
                </el-dialog>
                <!-- 弹窗 -->
                <el-dialog :title="dialogTitle" :close-on-click-modal='closeOnClickModal' :visible.sync="dialogFormVisible" width="50%" @close="closeDailog">
                    <el-form>
                        <el-form-item v-if="isBankandCityShow" label="银行" :label-width="formLabelWidth">
                            <el-select v-model="dailogFrom.bankId" size='small' placeholder="选择银行" @change="changeBankId" style="width: 150px">
                                <el-option v-for="item in banksData" :key="item.autoId" :label="item.bankName" :value="item.autoId" />
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="isBankCardShow" label="银行卡" :label-width="formLabelWidth">
                            <el-select value-key="autoId" v-model="bankCardObj" size='small' placeholder="选择银行卡" @change="changeBankCardId" style="width: 250px">
                                <el-option v-for="item in bankCardData" :key="item.autoId" :label="item.cardName" :value="item" />
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="isBankCardShow" label="51卡ID" :label-width="formLabelWidth">
                            {{bankCardObj.cardId51}}
                        </el-form-item>
                        <el-form-item label="名称" :label-width="formLabelWidth">
                            <el-input v-model.trim="dailogFrom.title" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item v-if="isBankCardShow" label="图片链接:" :label-width="formLabelWidth">
                            <img :src="dailogFrom.imageUrl" alt="" style="width:200px;height:110px;"/>
                        </el-form-item>
                        <section v-else>
                            <el-form-item label="图片链接" :label-width="formLabelWidth">
                                <el-form :inline="true">
                                    <el-form-item>
                                        <el-input v-model.trim="dailogFrom.imageUrl" style="width:250px;" size="small"/>
                                    </el-form-item>
                                    <el-form-item>
                                        <el-upload class="upload-demo" :headers="headers" :with-credentials="withCredentials" name="multipartFile" ref="upload" :action="uploadURL" :on-exceed="handleExceed" :on-remove="handleRemove" :on-success='handleSuccess' :file-list="fileList" :limit="1" :before-upload="beforeAvatarUpload">
                                            <el-button size="small" type="primary">点击上传</el-button>
                                        </el-upload>
                                    </el-form-item>
                                </el-form>
                            </el-form-item>
                            <el-form-item :label-width="formLabelWidth">
                                只能上传jpg/jpeg/png文件，且不超过10M
                            </el-form-item>
                        </section>
                        <el-form-item label="跳转链接" :label-width="formLabelWidth">
                            <el-input v-model.trim="dailogFrom.link" :disabled="isBankCardShow" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item label="排序" :label-width="formLabelWidth">
                            <el-input v-model.trim="dailogFrom.sort" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item label="激活时间" :label-width="formLabelWidth">
                            <el-date-picker v-model="dailogFrom.activateTime" type="datetime" value-format='yyyy-MM-dd HH:mm:ss' placeholder="选择日期时间" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item label="到期时间" :label-width="formLabelWidth">
                            <el-date-picker v-model="dailogFrom.expireTime" type="datetime" value-format='yyyy-MM-dd HH:mm:ss' placeholder="选择日期时间" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item v-if="activeName === '1002'" label="角标" :label-width="formLabelWidth">
                            <el-input v-model.trim="dailogFrom.hotTag" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item label="规则" :label-width="formLabelWidth">
                            <el-input :maxlength='100' type='textarea' :rows="2" v-model.trim="dailogFrom.remark" style="width:250px;" size="small"/>
                        </el-form-item>
                        <el-form-item label="活动状态" :label-width="formLabelWidth">
                            <el-select v-model="dailogFrom.disabled" style="width:150px;" placeholder="请选择活动状态" size="small">
                                <el-option label="启用" value=0 />
                                <el-option label="禁用" value=1 />
                            </el-select>
                        </el-form-item>
                        <!-- {{cityInput.code}} {{allCityCode}} -->
                        <el-form-item v-if="isBankandCityShow" label="开放城市" :label-width="formLabelWidth">
                            <el-form :inline="true" size='small'>
                                <el-form-item>
                                    <div class="cityName-div">
                                        <span v-if="cityInput.code.toString() == allCityCode.toString()">全国</span>
                                        <span v-else>{{cityInput.value !== '' ? cityInput.value.join(',') : ''}}</span>
                                    </div>
                                    <el-button type="primary" @click.stop="clickToSelectCities">选择城市</el-button>
                                </el-form-item>
                            </el-form>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="confirm">确 定</el-button>
                    </div>
                </el-dialog>
                <!-- 城市选择 -->
                <el-dialog title="城市选择" :close-on-click-modal='closeOnClickModal' :visible.sync="cityCodeVisible" width="70%" @close="closeCityDailog" @open="openCityDailog">
                    <div v-loading="cityLoading" element-loading-text="拼命加载中">
                        <div class="current-city">
                            <span>当前选择</span>
                            <el-tag v-for="tag in currentSelectedCities" :key="tag.code" closable @close="handleClose(tag)" type="info">
                                {{tag.name}}
                            </el-tag>
                        </div>
                        <el-form>
                            <el-form-item class="citysearch">
                                <el-input class="input-box" v-model.trim="citiesName" style="width:700px;"/>
                                <el-button class="check-btn" size="small" @click="clickCheckedBtnEvent">选中</el-button>
                                <el-checkbox class="allcheckbox" v-model="isWholeCountry" @change='changeAllcity'>全国</el-checkbox>
                            </el-form-item>
                            <div class="cities-box">
                                <el-tree :data="cityAreaData.provinces" show-checkbox node-key="code" :default-checked-keys="currentSelectedCitiesCode" @check-change="handleCheckChange" ref="tree" :props="defaultProps"/>
                            </div>
                        </el-form>
                    </div>
                    <span slot="footer">
                        <el-button size="small" @click="cityCodeVisible = false">取 消</el-button>
                        <el-button size="small" type="primary" @click="clickConfirmBtn">确 定</el-button>
                    </span>
                </el-dialog>
            </div>
        </div>
    </section>
</template>

<script>
import * as api from "../../api/api";
import { cityAreaData } from "../../common/js/cityCode.js";
export default {
    data() {
        return {
            closeOnClickModal: false,

            activeName: "2001", //tab栏默认展示

            listLoading: false, //加载loading
            tableData: [], // 数据列表

            dialogFormVisible: false,
            formLabelWidth: "180px",
            dailogType: "", // 弹窗类型
            dialogTitle: "", // 弹窗标题
            // 弹窗数据

            bankCardObj: {},
            dailogFrom: {
                title: "", //名称
                imageUrl: "", //图片链接
                link: "", //跳转链接
                sort: "", //排序
                activateTime: "", //激活时间
                expireTime: "", //到期时间
                remark: "", //活动规则
                bankId: "", //银行
                openCity: "", // 选择城市
                disabled: "", //活动状态
                hotTag: "", // 角标
                cardId: "" // 银行卡id
            },

            uploadURL: `${api.baseURL}/uploadFile`,
            headers: {
                token: window.sessionStorage.token
            },
            withCredentials: true, // 支持发送 cookie 凭证信息
            fileList: [],
            // 文章列表
            articleListCurPage: 1,
            articleListPageSize: 10,
            articleListTotalPage: 0,
            articleList: [],
            articleFormData: {
                status: "0"
            },
            articleDialogFormVisible: false,
            articleTypes: [],
            // tab栏 对应code及调用接口
            tabapiMap: [
                //     {
                //     code: '2002',
                //     tabName: '主图配置',
                //     request: mainAdPointList
                // },
                {
                    code: "2001",
                    tabName: "banner配置",
                    request: api.bannerAdPointList
                },
                {
                    code: "2003",
                    tabName: "文章配置",
                    request: api.getArticles
                },
                {
                    code: "1001",
                    tabName: "今日推荐",
                    request: api.currentRecommendAdPointList
                },
                {
                    code: "1002",
                    tabName: "热门银行",
                    request: api.hotBankAdPointList
                },
                {
                    code: "1003",
                    tabName: "好卡推荐",
                    request: api.goodCardAdPointList
                },
                {
                    code: "2004",
                    tabName: "活动配置",
                    request: api.benefitActivityList
                }
            ],

            // 图片地址栏 默认样式(监听tab切换更换样式)
            imageClass: {
                width: "140px",
                height: "25px"
            },
            // banner配置样式
            imageBanner: {
                width: "140px",
                height: "25px"
            },
            // 信用卡图片 样式
            imageCard: {
                width: "140px",
                height: "84px"
            },
            // 银行图标样式
            imageBank: {
                width: "50px",
                height: "50px"
            },

            banksData: [], // 银行名称列表

            bankCardData: [], // 银行卡列表

            // 银行卡选择框是否展示 图片预览 跳转链接禁点
            isBankCardShow: false,

            isBankandCityShow: false,
            cityCodeVisible: false,

            cityAreaData: {},
            isWholeCountry: false,
            citiesName: "",
            currentSelectedCities: [],
            currentSelectedCitiesCode: [],

            // 选择城市展示内容
            cityInput: {
                code: "",
                value: ""
            },
            editFormCityName: [],
            editFormCityCode: [],

            defaultProps: {
                children: "cities",
                label: "name",
                isLeaf: "leaf"
            },
            cityLoading: false,

            allCityCode: [],
            allCityName: []
        };
    },
    watch: {
        dailogType() {
            this.dailogType === "add"
                ? (this.dialogTitle = "新增")
                : (this.dialogTitle = "编辑");
        },

        activeName() {
            // 监听activeName 前三个展示城市和银行 后三个不展示
            if (
                this.activeName === "2002" ||
                this.activeName === "2001" ||
                this.activeName === "2003" ||
                this.activeName === "2004"
            ) {
                this.isBankandCityShow = false;
            }
            // 银行选择框 和选择城市框是否展示
            if (
                this.activeName === "1001" ||
                this.activeName === "1002" ||
                this.activeName === "1003"
            ) {
                this.isBankandCityShow = true;
            }
            // 银行卡选择框是否展示
            if (this.activeName === "1003") {
                this.isBankCardShow = true;
            } else {
                this.isBankCardShow = false;
            }
            // 监听activeName 根据tab切换样式
            if (this.activeName === "2001") {
                this.imageClass = this.imageBanner;
            }
            if (this.activeName === "1002") {
                this.imageClass = this.imageBank;
            }
            if (
                this.activeName === "1001" ||
                this.activeName === "1003" ||
                this.activeName === "2004"
            ) {
                this.imageClass = this.imageCard;
            }
        },
        // 监听城市选择数组
        currentSelectedCitiesCode() {
            if (
                this.currentSelectedCitiesCode.toString() ==
                this.allCityCode.toString()
            ) {
                // 如果选择的是全国数据
                this.isWholeCountry = true;
            } else {
                this.isWholeCountry = false;
            }
        }
    },
    methods: {
        // 全国checkBox选择事件
        changeAllcity(e) {
            if (e) {
                const cityArr = [];
                const cityCodeArr = [];
                for (const i of this.cityAreaData.provinces) {
                    for (const k of i.cities) {
                        cityArr.push(k);
                        cityCodeArr.push(k.code);
                        // this.$refs.tree.setChecked(k.code, true, false);
                    }
                }
                this.currentSelectedCities = cityArr;
                this.currentSelectedCitiesCode = cityCodeArr;
                this.$refs.tree.setCheckedKeys(cityCodeArr);
            } else {
                this.currentSelectedCities = [];
                this.$refs.tree.setCheckedKeys([]);
            }
        },
        // tab切换
        handleClick(tab) {
            // 重新请求接口
            this.tabapiMap.forEach(item => {
                if (tab.name === item.code) {
                    // 文章列表
                    if (tab.name === "2003") {
                        this.articleList = [];
                        this.listLoading = true;
                        this.getArticles(1);
                    } else {
                        // 数据清空
                        this.tableData = [];
                        this.publicRequest(item.request);
                    }
                }
            });
        },
        getArticles(pageNum) {
            return api
                .getArticles({
                    pageNum: pageNum || this.articleListCurPage + 1,
                    pageSize: 10
                })
                .then(res => {
                    this.articleList = res.data.list || [];
                    this.articleListTotalPage = res.data.total;
                    this.articleListCurPage = res.data.pageNum;
                })
                .finally(() => {
                    this.listLoading = false;
                });
        },
        // 截取时间
        formatDate(str) {
            if (!str) return "";
            const date = str.split("T")[0];
            const time = str.split("T")[1].split(".")[0];
            return `${date} ${time}`;
        },
        // 弹窗关闭
        closeDailog() {
            this.bankCardObj = {};
            this.bankCardData = [];
            this.dailogFrom = {
                title: "", //名称
                imageUrl: "", //图片链接
                link: "", //跳转链接
                sort: "", //排序
                activateTime: "", //激活时间
                expireTime: "", //到期时间
                remark: "", //活动规则
                bankId: "", //银行
                openCity: "", // 选择城市
                disabled: "", //活动状态
                hotTag: "", // 角标
                cardId: "" // 银行卡id
            };

            this.cityInput = {
                code: "",
                value: ""
            };
            this.fileList = [];

            this.editFormCityName = [];
            this.editFormCityCode = [];
            this.currentSelectedCities = [];
            this.currentSelectedCitiesCode = [];
            // 判断this.$refs.tree是否存在  否则会报错
            if (this.$refs.tree) {
                this.$refs.tree.setCheckedKeys([]);
            }
        },
        // 城市选择弹窗open
        openCityDailog() {
            this.currentSelectedCities = this.editFormCityName;
            this.currentSelectedCitiesCode = this.editFormCityCode;

            if (this.currentSelectedCitiesCode.length) {
                // 判断this.$refs.tree是否存在  否则会报错
                if (this.$refs.tree) {
                    this.$refs.tree.setCheckedKeys(
                        this.currentSelectedCitiesCode,
                        true
                    );
                }
            }
        },
        // 打开选择城市弹窗
        clickToSelectCities() {
            this.cityCodeVisible = true;
        },
        // 关闭选择城市弹窗
        closeCityDailog() {
            this.getAllCityCode();
            this.currentSelectedCities = this.editFormCityName;
            this.currentSelectedCitiesCode = this.editFormCityCode;
            this.$refs.tree.setCheckedKeys(this.currentSelectedCitiesCode);
        },
        // 点击选择城市确定按钮
        clickConfirmBtn() {
            const cities = [];
            for (const k of this.currentSelectedCities) {
                cities.push(k.name);
            }

            // cityInput 新增和编辑所用弹窗  展示的城市名及code数据
            this.cityInput.code = this.currentSelectedCitiesCode;
            this.cityInput.value = cities;

            // 拼接 城市code和name对象数组
            const cityAndcodeArr = [];
            for (let i = 0; i < cities.length; i++) {
                const newObj = {};
                newObj.name = cities[i];
                newObj.code = this.currentSelectedCitiesCode[i];
                cityAndcodeArr.push(newObj);
            }

            this.editFormCityName = cityAndcodeArr;
            this.editFormCityCode = this.currentSelectedCitiesCode;

            this.cityCodeVisible = false;
        },
        // 点击"选中"按钮
        clickCheckedBtnEvent() {
            let citiesName;
            if (this.citiesName.indexOf(",") !== -1) {
                citiesName = this.citiesName.split(",");
            } else if (this.citiesName.indexOf(" ") !== -1) {
                citiesName = this.citiesName.split(" ");
            } else if (this.citiesName.indexOf("，") !== -1) {
                citiesName = this.citiesName.split("，");
            } else {
                citiesName = [this.citiesName];
            }
            if (this.citiesName && citiesName.length) {
                for (const i of this.cityAreaData.provinces) {
                    for (const k of i.cities) {
                        for (const n in citiesName) {
                            if (
                                k.name == citiesName[n] &&
                                this.currentSelectedCitiesCode.indexOf(
                                    k.code
                                ) == -1
                            ) {
                                this.currentSelectedCities.push(k);
                                this.currentSelectedCitiesCode.push(k.code);
                                this.$refs.tree.setCheckedKeys(
                                    this.currentSelectedCitiesCode,
                                    true
                                );
                            }
                        }
                    }
                }
            }
        },
        // 选择银行change
        changeBankId(bankId) {
            // if (this.activeName !== "1002") return;
            // if (bankId) {
            //     this.banksData.forEach(item => {
            //         if (bankId === item.autoId) {
            //             this.dailogFrom.imageUrl = item.imageUrl;
            //         }
            //     });
            // } else {
            //     this.dailogFrom.imageUrl = "";
            // }

            // 热门银行1002 需要 取图片地址
            if (this.activeName == "1002") {
                if (bankId) {
                    this.banksData.forEach(item => {
                        if (bankId === item.autoId) {
                            this.dailogFrom.imageUrl = item.imageUrl;
                        }
                    });
                } else {
                    this.dailogFrom.imageUrl = "";
                }
            }

            // 好卡推荐1003 需要
            if (this.activeName == "1003") {
                this.bankCardObj = {};
                api.getBankCardList({ bankId: bankId }).then(res => {
                    this.bankCardData = res.data;
                });
            }
        },
        // 选择银行卡 change
        changeBankCardId(e) {
            this.dailogFrom.title = e.cardName;
            this.dailogFrom.imageUrl = e.imageUrl;
            this.dailogFrom.link = e.cardLink;
            this.dailogFrom.cardId = e.autoId;
        },
        // 选择城市checkBox
        handleCheckChange() {
            this.currentSelectedCities = this.$refs.tree.getCheckedNodes(true);
            this.currentSelectedCitiesCode = this.$refs.tree.getCheckedKeys(
                true
            );
        },
        // 关闭tag
        handleClose(tag) {
            this.currentSelectedCities.splice(
                this.currentSelectedCities.indexOf(tag),
                1
            );
            this.currentSelectedCitiesCode.splice(
                this.currentSelectedCitiesCode.indexOf(tag.code),
                1
            );
            this.$refs.tree.setCheckedKeys(
                this.currentSelectedCitiesCode,
                true
            );
        },
        // 判断两个年月日时分秒的大小
        compareDate(d1, d2) {
            return (
                new Date(d1.replace(/-/g, "/")) >
                new Date(d2.replace(/-/g, "/"))
            );
        },
        // 保存/编辑
        confirm() {
            if (!this.dailogFrom.bankId && this.isBankandCityShow) {
                this.$message.error("请选择银行!");
                return false;
            }
            if (!this.dailogFrom.title) {
                this.$message.error("请输入名称!");
                return false;
            }
            if (!this.dailogFrom.imageUrl) {
                this.$message.error("请上传图片!");
                return false;
            }
            if (!this.dailogFrom.link) {
                this.$message.error("请输入跳转链接!");
                return false;
            }
            if (
                !this.dailogFrom.sort ||
                !/^[0-9]+$/.test(this.dailogFrom.sort)
            ) {
                this.$message.error("请输入正确排序!");
                return false;
            }
            if (!this.dailogFrom.activateTime) {
                this.$message.error("请选择激活时间!");
                return false;
            }
            if (!this.dailogFrom.expireTime) {
                this.$message.error("请选择到期时间!");
                return false;
            }
            if (
                this.compareDate(
                    this.dailogFrom.activateTime,
                    this.dailogFrom.expireTime
                )
            ) {
                this.$message.error("激活时间不能大于到期时间!");
                return false;
            }
            // if (!this.dailogFrom.remark) {
            //     this.$message.error("请输入规则!")
            //     return false;
            // }
            if (!this.dailogFrom.disabled) {
                this.$message.error("请选择状态!");
                return false;
            }
            if (!this.isBankandCityShow) {
                this.dailogFrom.bankId = null;
                this.dailogFrom.openCity = null;
            } else {
                if (Array.isArray(this.cityInput.code)) {
                    this.dailogFrom.openCity = this.cityInput.code.join(",");
                } else {
                    this.dailogFrom.openCity = this.cityInput.code;
                }

                // 如果没有选择银行或者选择的全国 将值赋为9999
                if (
                    !this.dailogFrom.openCity ||
                    this.dailogFrom.openCity == this.allCityCode.toString()
                ) {
                    this.dailogFrom.openCity = "9999";
                }
            }

            // 添加position参数
            this.dailogFrom.position = this.activeName;

            if (this.dailogType === "add") {
                this.addAdPointFun(); // 新增
            } else {
                this.updateAdPointFun(); // 更新
            }
        },
        // 获取银行名称列表
        getBankNameList() {
            api.bankNameList().then(res => {
                this.banksData = res.data;
            });
        },
        getArticlesTypes() {
            api.getArticleTypes().then(res => {
                this.articleTypes = res.data;
            });
        },
        // 新增
        addModel() {
            this.dailogType = "add";
            if (this.activeName == "2003") {
                this.articleFormData = {
                    status: "0"
                };
                this.articleDialogFormVisible = true;
            } else {
                this.dialogFormVisible = true;
            }
        },
        editModelArticle(rowData) {
            this.dailogType = "edit";
            this.articleFormData = Object.assign({}, rowData);
            this.articleFormData.status = this.articleFormData.status.toString();
            this.articleFormData.top = this.articleFormData.top.toString();
            this.articleDialogFormVisible = true;
        },
        articleFormCancel() {
            this.articleDialogFormVisible = false;
        },
        // 更新新增文章确认
        articleFormConfirm() {
            // checkout filed
            if (!this.articleFormData.mainTitle) {
                this.$message.error("请输入主标题!");
                return false;
            }
            if (!this.articleFormData.subTitle) {
                this.$message.error("请输入副标题!");
                return false;
            }
            if (this.articleFormData.type == undefined) {
                this.$message.error("请选择文章类型!");
                return false;
            }

            if (!this.articleFormData.imageUrl) {
                this.$message.error("请上传图片!");
                return false;
            }
            if (!this.articleFormData.link) {
                this.$message.error("请输入跳转链接!");
                return false;
            }
            if (this.articleFormData.top == undefined) {
                this.$message.error("请输选择文章是否置顶!");
                return false;
            }
            if (this.articleFormData.status == undefined) {
                this.$message.error("请输选择文章是否启用!");
                return false;
            }
            this.articleFormData.status = parseInt(
                this.articleFormData.status,
                10
            );
            this.articleFormData.top = parseInt(this.articleFormData.top, 10);
            const confirmAction =
                this.dailogType === "edit" ? api.updateArticle : api.addArticle;
            confirmAction(this.articleFormData).then(() => {
                this.getArticles(1);
                this.articleDialogFormVisible = false;
            });
        },
        changeArticleListPage(pageNum) {
            return this.getArticles(pageNum);
        },
        // 编辑
        editModel(rowData) {
            this.dailogType = "edit";
            for (const key in rowData) {
                this.dailogFrom[key] = rowData[key];
                // 状态字段 置为字符串
                if (key === "disabled") {
                    this.dailogFrom.disabled = rowData[key].toString();
                }
            }
            if (this.isBankCardShow) {
                api.getBankCardList({ bankId: rowData.bankId }).then(res => {
                    this.bankCardData = res.data;
                    this.bankCardObj.autoId = rowData.cardId;
                    this.bankCardData.forEach(item => {
                        if (item.autoId == rowData.cardId) {
                            this.bankCardObj.cardId51 = item.cardId51;
                            return;
                        }
                    });
                });
            }
            if (this.isBankandCityShow && rowData.openCity) {
                let cityNameArr = [];
                let cityCodeArr = [];
                if (rowData.openCity == "9999") {
                    cityCodeArr = this.allCityCode;
                    cityNameArr = this.allCityName;
                    this.cityInput.value = cityNameArr;
                    this.cityInput.code = this.allCityCode;
                } else {
                    cityNameArr = this.getcityName(rowData.openCity.split(","));
                    cityCodeArr = rowData.openCity.split(",");
                    this.cityInput.value = cityNameArr;
                    this.cityInput.code = rowData.openCity;
                }

                const cityAndcodeArr = [];
                for (let i = 0; i < cityNameArr.length; i++) {
                    const newObj = {};
                    newObj.name = cityNameArr[i];
                    newObj.code = cityCodeArr[i];
                    cityAndcodeArr.push(newObj);
                }
                this.editFormCityName = cityAndcodeArr;
                this.editFormCityCode = cityCodeArr;
            }
            this.dialogFormVisible = true;
        },

        // 通过cityCode数组获取城市名数组
        getcityName(cityCode) {
            const arr = [];
            for (const k of this.cityAreaData.provinces) {
                for (const n of k.cities) {
                    for (const i in cityCode) {
                        if (n.code === cityCode[i]) {
                            arr.push(n.name);
                        }
                    }
                }
            }
            return arr;
        },

        // 文件移除事件
        handleRemove() {
            this.fileList = [];
            this.dailogFrom.imageUrl = "";
            this.articleFormData.imageUrl = "";
        },
        // 超出上传限制提示
        handleExceed() {
            this.$message.warning("当前限制只能上传 1 个文件");
        },
        // 上传成功
        handleSuccess(res) {
            // this.$message.success("上传成功！");
            // if (this.activeName === "2003") {
            //   this.articleFormData.imageUrl = res.data;
            // } else {
            //   this.dailogFrom.imageUrl = res.data;
            // }
            if (res.code === 1) {
                this.$message.success("上传成功！");
                if (this.activeName === "2003") {
                    this.articleFormData.imageUrl = res.data;
                } else {
                    this.dailogFrom.imageUrl = res.data;
                }
            } else {
                this.$message.error(res.message);
                if (res.code === 40100) {
                    this.$router.push({
                        path: "login"
                    });
                }
            }
        },
        // 文件大小 文件名判断
        beforeAvatarUpload(file) {
            const fileName = file.name;
            const index = fileName.lastIndexOf(".");
            const fileFormat = fileName.substring(index + 1, fileName.length);
            const isName =
                fileFormat === "png" ||
                fileFormat === "jpg" ||
                fileFormat === "jpeg";
            const isLt150KB = file.size / 1024 < 150;
            if (!isName) {
                this.$message.error("上传文件只能是 png/jpg/jpeg 格式!");
                this.fileList = [];
            }
            if (!isLt150KB) {
                this.$message.error("上传文件大小不能超过 150KB!");
                this.fileList = [];
            }
            return isName && isLt150KB;
        },
        //请求接口公共方法
        publicRequest(requestURL) {
            this.listLoading = true;
            requestURL()
                .then(res => {
                    this.listLoading = false;
                    this.tableData = res.data;
                })
                .catch(() => {
                    this.listLoading = false;
                    this.$message.error("网络挂啦，请求不到数据！");
                });
        },
        // 调用新增接口
        addAdPointFun() {
            api.addAdPoint(this.dailogFrom).then(() => {
                this.tabapiMap.forEach(item => {
                    if (this.activeName === item.code) {
                        this.publicRequest(item.request);
                    }
                });
                this.$message.success("新增成功!");
                this.dialogFormVisible = false;
            });
        },
        // 调用更新接口
        updateAdPointFun() {
            api.updateAdPoint(this.dailogFrom).then(() => {
                this.tabapiMap.forEach(item => {
                    if (this.activeName === item.code) {
                        this.publicRequest(item.request);
                    }
                });
                this.$message.success("更新成功!");
                this.dialogFormVisible = false;
            });
        },
        // 获取全部城市code
        getAllCityCode() {
            const allCityCodeArr = [];
            const allCityName = [];
            for (const i of this.cityAreaData.provinces) {
                for (const k of i.cities) {
                    allCityCodeArr.push(k.code);
                    allCityName.push(k.name);
                    this.allCityCode = allCityCodeArr;
                    this.allCityName = allCityName;
                }
            }
        }
    },
    mounted() {
        this.cityAreaData = cityAreaData;
        // 获取银行名称列表
        this.getBankNameList();
        this.getArticlesTypes();
        // 请求第一个tab的数据
        this.publicRequest(api.bannerAdPointList);

        // 获取全部城市code name
        this.getAllCityCode();
    }
};
</script>

<style>
.btn-margin {
    margin: 10px;
}

.cityName-div {
    display: inline-block;
    width: 300px;
    border: 1px solid #eee;
    height: 100px;
    max-height: 100px;
    overflow-y: auto;
}

.current-city {
    max-height: 200px;
    margin-bottom: 10px;
    overflow-y: auto;
}

.cities-box {
    border: 1px solid #eee;
    max-height: 300px;
    overflow-y: auto;
}

.cities-box .el-tree > .el-tree-node > .el-tree-node__content:nth-child(1) {
    height: 40px;
    background-color: #eee;
}

.cities-box .el-tree-node__children:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.cities-box .el-tree-node__children .el-tree-node__content {
    float: left;
}
</style>
